package com.wishwingz.klipper;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.webkit.CookieSyncManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

public class MainActivity extends SherlockFragmentActivity {
	static final String DEFAULT_URL = "http://1.234.7.150:5007/";

	private WebView wv;
	private Handler mHandler;
	private boolean mFlag = false;
	private ActionBar bar;

	@SuppressLint({ "SetJavaScriptEnabled", "Recycle", "HandlerLeak" })
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		startActivity(new Intent(this, SplashActivity.class));
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		CookieSyncManager.createInstance(this);

		bar = getSupportActionBar();

		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				if (msg.what == 0) {
					mFlag = false;
				}
			}
		};

		wv = (WebView) findViewById(R.id.mainWebView);
		wv.getSettings().setJavaScriptEnabled(true);
		wv.setWebViewClient(new MyWebView());
		wv.setWebChromeClient(new MyChromeClient());

		wv.loadUrl(DEFAULT_URL);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			if (wv.canGoBack()) {
				wv.goBack();
				return false;
			} else {
				if (!mFlag) {
					Toast.makeText(MainActivity.this,
							"'뒤로'버튼을 한 번 더 누르시면 종료됩니다.", Toast.LENGTH_SHORT)
							.show();
					mFlag = true;
					mHandler.sendEmptyMessageDelayed(0, 2000);
					return false;
				} else {
					finish();
				}
			}
		}
		return super.onKeyDown(keyCode, event);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getSupportMenuInflater().inflate(R.menu.main_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			wv.loadUrl("http://1.234.7.150:5007/");
			bar.setDisplayHomeAsUpEnabled(false);
			break;
		case R.id.action_search:
			wv.loadUrl("http://1.234.7.150:5007/auto_cmp");
			bar.setDisplayHomeAsUpEnabled(true);
			break;
		case R.id.action_add:
			Intent i = new Intent(MainActivity.this, UploadActivity.class);
			startActivity(i);
			break;
		case R.id.sub_upload:
			wv.loadUrl("http://1.234.7.150:5007/myupload");
			bar.setDisplayHomeAsUpEnabled(true);
			break;
		case R.id.sub_scrap:
			wv.loadUrl("http://1.234.7.150:5007/scraplist");
			bar.setDisplayHomeAsUpEnabled(true);
			break;
		case R.id.sub_account:
			wv.loadUrl("http://1.234.7.150:5007/account");
			bar.setDisplayHomeAsUpEnabled(true);
			break;
		}
		return super.onOptionsItemSelected(item);
	}
}

class MyWebView extends WebViewClient {

	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {
		// TODO Auto-generated method stub
		view.loadUrl(url);
		return super.shouldOverrideUrlLoading(view, url);
	}

}

class MyChromeClient extends WebChromeClient {

	@Override
	public boolean onJsAlert(WebView view, String url, String message,
			JsResult result) {
		// TODO Auto-generated method stub
		final JsResult res = result;

		new AlertDialog.Builder(view.getContext())
				.setTitle("PriShare")
				.setIcon(R.drawable.p_icon_logoball)
				.setMessage(message)
				.setPositiveButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								res.confirm();
							}
						}).setCancelable(false).create().show();
		return true;

	}

	@Override
	public boolean onJsConfirm(WebView view, String url, String message,
			JsResult result) {
		// TODO Auto-generated method stub
		final JsResult res = result;
		new AlertDialog.Builder(view.getContext())
				.setTitle("PriShare")
				.setIcon(R.drawable.p_icon_logoball)
				.setMessage(message)
				.setPositiveButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								res.confirm();
							}
						})
				.setNegativeButton(android.R.string.cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								res.cancel();
							}
						}).show();
		return true;
	}

}